

from rest_framework.generics import RetrieveAPIView, CreateAPIView, UpdateAPIView #用于保存数据
from .serializers import UserShowSerializers, UserEmailSerializers  #导入用户个人信息战士序列化器
from itsdangerous import TimedJSONWebSignatureSerializer as TJS
from users.serializers import CreateUserSerializer
from newmeiduomall.libs.yuntongxun.sms import CCP
from celery_tasks.sms.tasks import send_sms_code
from django_redis import get_redis_connection
from rest_framework.response import Response
from rest_framework.views import APIView
from django.shortcuts import render
from threading import Thread
from random import randint
# Create your views here.
from django.conf import settings





#
# def send_sms_code(mobile, sms_code):
#     ccp = CCP()
#     ccp.send_template_sms(mobile, [sms_code, '5'], 1)
# from users import serializers
from users import serializers
from users.models import User


class SMS_Code_View(APIView):

    def get(self, request, mobile):
        #获取手机号
        #验证手机号是否正确
        conn = get_redis_connection('sms_code')
        flag = conn.get('sms_code_flag_%s' % mobile)
        if flag:
            return Response({'error':'请求过于频繁'})



        #生成短信验证码
        # X = random.randint(1000-10000)
        sms_code = '%06d'%randint(0,999999)
        #生成一个管道对象
        pl = conn.pipeline()


        # 保存短信到redis
        # >>>>>>>>>>>>>>>>>>>>>>>>>>这里是在连接sms_code缓存数据库
        # conn = get_redis_connection('sms_code')
        pl.setex('sms_code_%s' % mobile, 300, sms_code)
        #这里写一个标志数据，用来控制同个用户在短时间内多次访问
        #管道pl，只是写入数据的时候用，在获取数据的时候还是用连接对象conn
        # pl.setex('sms_code_flag_%s' % mobile, 60, 2)
        #将数据一起传递给管道
        pl.execute()
        print(sms_code)
        #发送短信
        # ccp = CCP()
        # ccp.send_template_sms(mobile, [sms_code, '5'],1)
        #用线程异步发送短信，来解耗时的问题
        # t = Thread(target=send_sms_code, kwargs={'mobile': mobile, 'sms_code':sms_code})
        #启动线程
        # t.start()
        #下面开始使用celery
        send_sms_code.delay(mobile, sms_code)


        #返回ok
        return Response('OK')


class UserNameView(APIView):
    """
    判断用户名是不是重复，
    获取用户名APIView已经封装好了，所以直接用count判断即可
    """
    def get(self,request,username):

        count = User.objects.filter(username=username).count()


        return Response(

            {'count':count}

        )


class MobileView(APIView):
    """
    判断用户名是不是重复，
    获取用户名APIView已经封装好了，所以直接用count判断即可
    """
    def get(self,request,mobile):

        count = User.objects.filter(mobile=mobile).count()


        return Response(

            {'count':count}

        )


class UserView(CreateAPIView):

    # serializer_class = UserSerializers
    serializer_class = CreateUserSerializer
    # queryset = User.objects.all()

class UserShowView(RetrieveAPIView):
    """
        这个视图用来实现战士个人信息
    """
    #在这里制定一个序列化器
    serializer_class = UserShowSerializers
    #指定集合
    queryset = User.objects.all()
    #因为要返回user_id所以要重方法

    #重写这个方法是为了返回pk值即user_id
    def get_object(self):

        return self.request.user

class UserEmailView(UpdateAPIView):
    """
        保存更新邮箱
    """
    serializer_class = UserEmailSerializers

    # 重写get——object
    def get_object(self):
        return self.request.user


class UserEmailVifyView(APIView):
    """
    验证邮箱
    """
    #获取数据
    def get(self,request):
        token = request.query_params.get('token')

        #解密token
        tjs = TJS(settings.SECRET_KEY,300)
        try:
        #获取解密后的数据
            data = tjs.loads(token)
        except:
            return Response({'errors':"错误token"},status=400)

        #通过用户名，获取用户对象
        username = data.get('username')#这里用爽引号试试
        user = User.objects.get(username=username)

        #通过用户对象判断是谁的邮箱有效，然后修改它的邮箱
        user.email_active = True
        user.save()
        #返回邮箱验证状态
        return Response({'email_active':user.email_active})


# class youxiagyanzheng(APIView):
#     """
#     验证邮箱
#     """
#     # 获取token数据
#     token = request.query_params.get('token')
#
#     # 解密token
#     tjs = TJS(setting.SECRET_KEY, 300)
#     try:
#       data = tjs.loads(token)
#     except:
#       return Response({'errors':'token值错误'}, status=400)
#     # 获取解密后的数据
#     username = data.get('username')
#     # 通过用户名，获取用户对象
#     user = User.objects.get(username=username)
#     # 通过用户对象判断是谁的邮箱有效，然后修改它的邮箱
#     user.email_active = True
#     user.save()
#     # 返回邮箱验证状态
#     return Response({'email_active':user.email_active})
